const { promisify } = require('util');

const figlet = promisify(require('figlet'));
const clear = require('clear');
const chalk = require('chalk');
const open = require('open');

const log = content => console.log(chalk.green(content));
const { clone } = require('./download');

module.exports.init = async name =>  {
  // 欢迎界面
  clear();
  const data = await figlet('KKB Welcome');
  log(data);

  // 下载模板
  await clone('github:cellinlab/vue-template', name);

  // 安装依赖
  log('安装依赖');
  await spawn(process.platform === 'win32' ? 'npm.cmd' : 'npm', ['install'], { cwd: `./${name}` });
  log(chalk.green(`
安装完成：
To get Start:
===========================
cd ${name}
npm run serve
===========================
 `))

  // 启动项目
  open(`http://localhost:8080`);
  await spawn(process.platform === 'win32' ? 'npm.cmd' : 'npm', ['run', 'serve'], { cwd: `./${name}` });
};

// 对接输出流
const spawn = async (...args) => {
  const { spawn } = require('child_process');
  return new Promise((resolve, reject) => {
    const proc = spawn(...args);
    proc.stdout.pipe(process.stdout);
    proc.stderr.pipe(process.stderr);
    proc.on('close', () => {
      resolve();
    });
  });
};